package com.topchain.licenceverify.bean;

import com.topchain.licenceverify.exception.SignException;
import com.topchain.licenceverify.intfs.ISign;
import com.topchain.licenceverify.log.CryptoLog;
import com.topchain.licenceverify.log.CryptoLogFactory;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * @DESCRIPTION: 验证签名类
 * @USER: shg
 * @DATE: 2023/4/11 15:44
 */
public class RSA implements ISign {
    private static final CryptoLog log = CryptoLogFactory.getLog(RSA.class);
    private static final String KEY_ALGORITHM = "RSA";

    @Override
    public boolean verify(byte[] data, PublicKey publicKey, byte[] sign, String signatureAlgorithm) throws SignException {
        boolean verify;
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(signatureAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            verify = signature.verify(sign);
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            log.error(e.getMessage());
            throw new SignException(e.getMessage(), e);
        }
        return verify;
    }
}
